package core;

import java.sql.*;

public class PgSQL {
	private Connection link = null;
	private Driver driver = null;
	
	public PgSQL(){
		try{
			driver = (Driver) Class.forName("org.postgresql.Driver").newInstance();
			DriverManager.registerDriver(driver);
		}catch(Exception e){
			e.printStackTrace();
		}
	}
	
	protected void finalize() throws Exception{
		close();
		DriverManager.deregisterDriver(driver);
	}
	
	public void connect(String database, String user, String password){
		if(link != null){
			close();
		}
		
		try{
			link = DriverManager.getConnection("jdbc:postgresql:" + database, user, password);
		}catch(SQLException e){
			e.printStackTrace();
		}
	}
	
	public void close(){
		try{
			link.close();
		}catch(SQLException e){
			e.printStackTrace();
		}finally{
			link = null;
		}
	}
	
	public ResultSet query(String sql){
		if(link == null){
			return null;
		}
		
		try{
			Statement st = link.createStatement();
			return st.executeQuery(sql);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;		
	}
	
	public ResultSet query(String sql, String ...strings){
		if(link == null){
			return null;
		}
		
		try{
			PreparedStatement st = link.prepareStatement(sql);
			for(int i = 0; i < strings.length; i++){
				st.setString(i + 1, strings[i]);
			}
			return st.executeQuery();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return null;
	}
	
	public int update(String sql){
		if(link == null){
			return -1;
		}
		
		try{
			Statement st = link.createStatement();
			return st.executeUpdate(sql);
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return -1;		
	}
	
	public int update(String sql, String ...strings){
		if(link == null){
			return -1;
		}
		
		try{
			PreparedStatement st = link.prepareStatement(sql);
			for(int i = 0; i < strings.length; i++){
				st.setString(i + 1, strings[i]);
			}
			return st.executeUpdate();
			
		}catch(Exception e){
			e.printStackTrace();
		}
		
		return -1;
	}
	
	public PreparedStatement prepareStatement(String sql){
		PreparedStatement st = null;
		try {
			st = link.prepareStatement(sql);
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return st;
	}
	
	static private PgSQL db = null;
	static public PgSQL getInstance(){
		if(db == null){
			db = new PgSQL();
			db.connect(Config.dbName, Config.dbUser, Config.dbPassword);
		}
		return db;
	}
}
